﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kTudu.Web.Models;
using System.Web.Security;
using kTudu.Web.Applications;
using kTudu.Web.Controllers.Base;
using kTudu.Web.Helpers;

namespace kTudu.Web.Controllers
{
    public class LoginController : BaseController
    {
        #region Properties

        protected UserClientApplication _application = null;

        #endregion

        #region Constructors

        public LoginController()
        {
            _application = _applicationFactory.GetApplication<UserClientApplication>();
        }

        #endregion


        public ActionResult LogOn()
        {
            if (Request.IsAuthenticated)
            {
                var cookie = System.Web.HttpContext.Current.Request.Cookies[CookieHelper.CookieName]["userName"];

                var user = _application.Get(cookie);

                CurrentUser = user;

                return RedirectToAction("index", "home");
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult LogOn(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (_application.IsValid(model.UserName, model.Password))
                {
                    var user = _application.Get(model.UserName);
                    
                    CurrentUser = user;

                    //if (model.Recordar)
                    //{
                    //    HttpCookie existingCookie = Request.Cookies["UserName"];
                    //    if (existingCookie != null)
                    //    {
                    //        // force to expire it
                    //        existingCookie.Value = model.UserName;
                    //        existingCookie.Expires = DateTime.Now.AddHours(-20);
                    //    }
                    //}

                    //HttpCookie newCookie = new HttpCookie("UserName", model.UserName);
                    //newCookie.Expires = DateTime.Today.AddMonths(12);
                    //Response.Cookies.Add(newCookie);
                    CookieHelper.SetCookie(model.UserName); // Cambiar por 365 dias
                    

                    FormsAuthentication.SetAuthCookie(model.UserName, model.Recordar);

                    return RedirectToAction("index", "home");
                }
                else
                {
                    ModelState.AddModelError("InvalidUserPassword", "Usuario o contraseña inválida.");
                }
            }

            return View();
        }
    }
}
